var config = require('../config'), uuid = require('node-uuid');

var Session = function(sessionID){
	this.id = sessionID;
	this.data = {};
	var d = new Date();
	this.refreshTime = d.getTime();
}

Session.prototype.getID = function(){
	return this.id;
}

Session.prototype.attr = function(key, value){
	if(arguments.length==2){
		this.data[key] = value;
	}else if(arguments.length==1){
		return this.data[key];
	}else{
		return null;
	}
}

Session.prototype.getRefreshTime = function(){
	return this.refreshTime;
}

Session.prototype.refresh = function(){
	var d = new Date();
	this.refreshTime = d.getTime();
}

Session.prototype.isTimeOut = function(){
	var d = new Date();
	var currentTime = d.getTime();
	if(currentTime>(config.sessionTimeout+this.refreshTime)){
		return true;
	}
	return false;
}

Session.prototype.getData = function(){
	return this.data;
}

var SessionManager = function(){
	this.sessions = {};
}

SessionManager.prototype.create = function(){
	var sessionID = uuid();
	var session = new Session(sessionID);
	this.sessions[sessionID] = session;
	return session;
}

SessionManager.prototype.getSession = function(sessionID){
	var session = this.sessions[sessionID];
	if(!session){
		return null;
	}
	if(session.isTimeOut()){
		this.sessions[sessionID] = null;
		return null;
	}
	return session;
}

SessionManager.prototype.remove = function(sessionID){
	this.sessions[sessionID] = null;
}

exports.SessionManager = SessionManager;
exports.Session = Session;